/**
 * 
 */
package com.feonix.common.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import com.feonix.common.BaseInfo;
import com.feonix.common.permission.AbsPermissionAdapter;
import com.feonix.common.permission.PermissionAdapterHander;
import com.feonix.common.permission.PermissionConfig;
import com.feonix.common.permission.PermissionUtil;
import com.feonix.common.util.StringUtil;

/**
 * @CopyRight (c)1993-2017
 * @Project m-complat-common
 * @Comments 权限过滤器
 * @NameSpace com.feonix.common.interceptor
 * @Author Feonixzw
 * @CreateDate 2018年1月4日
 */
public class PermissionInterceptor extends BaseInterceptor {

	@Override
	public boolean before(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			Object object) {
		String str1 = httpServletRequest.getServletPath() + (StringUtil.isNotEmpty(httpServletRequest.getQueryString())
				? "?" + httpServletRequest.getQueryString() : "");
		this.logger.debug("Operation Url:" + str1);
		boolean result = true;
		boolean isNeedCheck = PermissionUtil.isNeedCheck(object);
		if (isNeedCheck) {
			PermissionConfig permissionConfig = PermissionUtil.getPermissionConfig(object);
			String str2 = permissionConfig.getAdapter();
			AbsPermissionAdapter absPermissionAdapter = PermissionAdapterHander.getAdapterWithDefault(str2);
			switch (permissionConfig.getValidModal().ordinal()) {
			case 2:
				result = absPermissionAdapter.checkControllerWithURL(PermissionUtil.getStructure(object), str1);
				break;
			case 1:
				result = absPermissionAdapter.checkController(PermissionUtil.getStructure(object));
				break;
			default:
				switch (absPermissionAdapter.getValidModal().ordinal()) {
				case 1:
					result = absPermissionAdapter.checkController(PermissionUtil.getStructure(object));
					break;
				case 2:
					result = absPermissionAdapter.checkControllerWithURL(PermissionUtil.getStructure(object), str1);
					break;
				default:
					result = absPermissionAdapter.checkController(PermissionUtil.getStructure(object));
				}
				break;
			}
		}
		if (result) {
			return true;
		}
		try {
			httpServletResponse.sendRedirect(BaseInfo.getContextPath() + "/error/forbidden");
		} catch (Exception localException) {
			this.logger.error("sendRedirect error", localException);
		}
		return false;
	}

	@Override
	public void after(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object,
			ModelAndView modelAndView) {
		// TODO Auto-generated method stub

	}

	@Override
	public void complete(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object,
			Exception exception) {
		// TODO Auto-generated method stub

	}

}
